import { useState, useEffect } from 'react';
import {
    Card, Text, Group, Stack, TextInput, Button, Table, Modal,
    ScrollArea, Pagination, Badge, Loader, ActionIcon, Popover,
    Textarea
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import { IconPlant2, IconSearch, IconEdit, IconTrash, IconEye, IconPlus } from '@tabler/icons-react';
import axios from 'axios';

interface PlantDisease {
    id: number;
    en_name: string;
    cn_name: string;
    [key: string]: any;
}

interface SearchParams {
    page: number;
    per_page: number;
    en_name: string;
    cn_name: string;
}

const API_BASE_URL = 'http://localhost:8980';

const PlantDiseaseManagement = () => {
    const [diseases, setDiseases] = useState<PlantDisease[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [total, setTotal] = useState<number>(0);
    const [searchParams, setSearchParams] = useState<SearchParams>({
        page: 1,
        per_page: 10,
        en_name: '',
        cn_name: ''
    });

    const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
    const [isEditModalVisible, setIsEditModalVisible] = useState<boolean>(false);
    const [currentDisease, setCurrentDisease] = useState<PlantDisease | null>(null);
    const [detailsOpened, setDetailsOpened] = useState(false);

    const form = useForm({
        initialValues: {
            en_name: '',
            cn_name: '',
            img_url: '',
            description: '',
            suggestion: ''
        },
        validate: {
            en_name: (value) => (value.length < 2 ? '英文名称至少2个字符' : null),
            cn_name: (value) => (value.length < 2 ? '中文名称至少2个字符' : null),
        },
    });

    const fetchDiseases = async () => {
        setLoading(true);
        try {
            const queryParams = new URLSearchParams();
            queryParams.append('page', searchParams.page.toString());
            queryParams.append('per_page', searchParams.per_page.toString());
            if (searchParams.en_name) queryParams.append('en_name', searchParams.en_name);
            if (searchParams.cn_name) queryParams.append('cn_name', searchParams.cn_name);

            const response = await axios.get(`/app-api/disease/list?${queryParams.toString()}`);
            if (response && response.data) {
                const items = response.data.diseases || [];
                const totalCount = response.data.pagination.total || 0;
                setDiseases(items);
                setTotal(totalCount);
            }
        } catch (error) {
            notifications.show({
                title: '获取病虫害列表失败',
                message: error instanceof Error ? error.message : '请稍后再试',
                color: 'red',
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchDiseases();
    }, [searchParams.page, searchParams.per_page]);

    const handleSearch = () => {
        setSearchParams(prev => ({ ...prev, page: 1 }));
        fetchDiseases();
    };

    const handleReset = () => {
        setSearchParams({
            page: 1,
            per_page: 10,
            en_name: '',
            cn_name: ''
        });
        fetchDiseases();
    };

    const handleAdd = async (values: typeof form.values) => {
        try {
            setLoading(true);
            await axios.post(`/app-api/disease`, values);
            notifications.show({
                title: '添加成功',
                message: '病虫害信息已添加',
                color: 'green',
            });
            setIsModalVisible(false);
            form.reset();
            fetchDiseases();
        } catch (error) {
            notifications.show({
                title: '添加失败',
                message: error instanceof Error ? error.message : '请稍后再试',
                color: 'red',
            });
        } finally {
            setLoading(false);
        }
    };

    const handleEdit = (disease: PlantDisease) => {
        setCurrentDisease(disease);
        form.setValues(disease);
        setIsEditModalVisible(true);
    };

    const handleEditSubmit = async (values: typeof form.values) => {
        if (!currentDisease) return;

        try {
            setLoading(true);
            await axios.put(`/app-api/disease/${currentDisease.id}`, values);
            notifications.show({
                title: '更新成功',
                message: '病虫害信息已更新',
                color: 'green',
            });
            setIsEditModalVisible(false);
            fetchDiseases();
        } catch (error) {
            notifications.show({
                title: '更新失败',
                message: error instanceof Error ? error.message : '请稍后再试',
                color: 'red',
            });
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (id: number) => {
        try {
            setLoading(true);
            await axios.delete(`/app-api/disease/${id}`);
            notifications.show({
                title: '删除成功',
                message: '病虫害信息已删除',
                color: 'green',
            });
            fetchDiseases();
        } catch (error) {
            notifications.show({
                title: '删除失败',
                message: error instanceof Error ? error.message : '请稍后再试',
                color: 'red',
            });
        } finally {
            setLoading(false);
        }
    };

    const openUserDetails = (disease: PlantDisease) => {
        setCurrentDisease(disease);
        setDetailsOpened(true);
    };

    return (
        <Stack gap="lg" p="md">
            <Card withBorder shadow="sm" padding="md">
                <Group justify="space-between" mb="md">
                    <Group>
                        <IconPlant2 size={24} style={{ color: 'var(--mantine-color-green-6)' }} />
                        <Text fw={500} size="lg">病虫害管理</Text>
                    </Group>
                    <Button
                        leftSection={<IconPlus size={16} />}
                        onClick={() => {
                            form.reset();
                            setIsModalVisible(true);
                        }}
                    >
                        新建病虫害
                    </Button>
                </Group>

                <Group mb="md">
                    <TextInput
                        placeholder="英文名称"
                        value={searchParams.en_name}
                        onChange={(e) => setSearchParams(prev => ({ ...prev, en_name: e.target.value }))}
                        style={{ flex: 1 }}
                    />
                    <TextInput
                        placeholder="中文名称"
                        value={searchParams.cn_name}
                        onChange={(e) => setSearchParams(prev => ({ ...prev, cn_name: e.target.value }))}
                        style={{ flex: 1 }}
                    />
                    <Button onClick={handleSearch} leftSection={<IconSearch size={16} />}>搜索</Button>
                    <Button variant="light" onClick={handleReset}>重置</Button>
                </Group>

                <ScrollArea>
                    <Table striped highlightOnHover withTableBorder>
                        <Table.Thead>
                            <Table.Tr>
                                <Table.Th>ID</Table.Th>
                                <Table.Th>英文名称</Table.Th>
                                <Table.Th>中文名称</Table.Th>
                                <Table.Th>操作</Table.Th>
                            </Table.Tr>
                        </Table.Thead>
                        <Table.Tbody>
                            {loading ? (
                                <Table.Tr>
                                    <Table.Td colSpan={4}>
                                        <Group justify="center" py="md">
                                            <Loader size="sm" />
                                            <Text>加载中...</Text>
                                        </Group>
                                    </Table.Td>
                                </Table.Tr>
                            ) : diseases.length === 0 ? (
                                <Table.Tr>
                                    <Table.Td colSpan={4}>
                                        <Text ta="center" py="md">没有找到匹配的病虫害信息</Text>
                                    </Table.Td>
                                </Table.Tr>
                            ) : diseases.map((disease) => (
                                <Table.Tr key={disease.id}>
                                    <Table.Td>{disease.id}</Table.Td>
                                    <Table.Td>{disease.en_name}</Table.Td>
                                    <Table.Td>{disease.cn_name}</Table.Td>
                                    <Table.Td>
                                        <Group gap="xs">
                                            <ActionIcon
                                                variant="subtle"
                                                color="blue"
                                                onClick={() => openUserDetails(disease)}
                                            >
                                                <IconEye size={16} />
                                            </ActionIcon>
                                            <ActionIcon
                                                variant="subtle"
                                                color="green"
                                                onClick={() => handleEdit(disease)}
                                            >
                                                <IconEdit size={16} />
                                            </ActionIcon>
                                            <Popover width={200} position="bottom" withArrow shadow="md">
                                                <Popover.Target>
                                                    <ActionIcon variant="subtle" color="red">
                                                        <IconTrash size={16} />
                                                    </ActionIcon>
                                                </Popover.Target>
                                                <Popover.Dropdown>
                                                    <Stack gap="sm">
                                                        <Text size="sm">确定要删除这条记录吗？</Text>
                                                        <Group justify="flex-end" gap="xs">
                                                            <Button variant="light" size="xs" color="gray">取消</Button>
                                                            <Button size="xs" color="red" onClick={() => handleDelete(disease.id)}>删除</Button>
                                                        </Group>
                                                    </Stack>
                                                </Popover.Dropdown>
                                            </Popover>
                                        </Group>
                                    </Table.Td>
                                </Table.Tr>
                            ))}
                        </Table.Tbody>
                    </Table>
                </ScrollArea>

                {total > searchParams.per_page && (
                    <Group justify="center" mt="md">
                        <Pagination
                            total={Math.ceil(total / searchParams.per_page)}
                            value={searchParams.page}
                            onChange={(page) => setSearchParams(prev => ({ ...prev, page }))}
                        />
                    </Group>
                )}
            </Card>

            {/* 详情模态框 */}
            <Modal
                opened={detailsOpened}
                onClose={() => setDetailsOpened(false)}
                title={
                    <Group gap="xs">
                        <IconPlant2 size={24} style={{ color: 'var(--mantine-color-green-6)' }} />
                        <Text size="lg" fw={600}>病虫害详情</Text>
                    </Group>
                }
                size="lg"
                centered
            >
                {currentDisease && (
                    <Stack gap="lg">
                        {/* {currentDisease.img_url && (
                            <Card withBorder>
                                <img
                                    src={currentDisease.img_url}
                                    alt={currentDisease.cn_name}
                                    // fit="contain"
                                    height={200}
                                />
                            </Card>
                        )} */}
                        <Table withColumnBorders>
                            <Table.Tbody>
                                <Table.Tr>
                                    <Table.Td style={{ width: '150px' }}>
                                        <Text fw={500} c="gray.6">ID</Text>
                                    </Table.Td>
                                    <Table.Td>
                                        <Text size="lg">{currentDisease.id}</Text>
                                    </Table.Td>
                                </Table.Tr>
                                <Table.Tr>
                                    <Table.Td>
                                        <Text fw={500} c="gray.6">英文名称</Text>
                                    </Table.Td>
                                    <Table.Td>
                                        <Text size="lg">{currentDisease.en_name}</Text>
                                    </Table.Td>
                                </Table.Tr>
                                <Table.Tr>
                                    <Table.Td>
                                        <Text fw={500} c="gray.6">中文名称</Text>
                                    </Table.Td>
                                    <Table.Td>
                                        <Text size="lg">{currentDisease.cn_name}</Text>
                                    </Table.Td>
                                </Table.Tr>
                                <Table.Tr>
                                    <Table.Td>
                                        <Text fw={500} c="gray.6">病虫害描述</Text>
                                    </Table.Td>
                                    <Table.Td>
                                        <Text size="lg">{currentDisease.description || '暂无描述'}</Text>
                                    </Table.Td>
                                </Table.Tr>
                                <Table.Tr>
                                    <Table.Td>
                                        <Text fw={500} c="gray.6">防治建议</Text>
                                    </Table.Td>
                                    <Table.Td>
                                        <Text size="lg">{currentDisease.suggestion || '暂无建议'}</Text>
                                    </Table.Td>
                                </Table.Tr>
                            </Table.Tbody>
                        </Table>
                    </Stack>
                )}
            </Modal>

            {/* 添加/编辑模态框 */}
            <Modal
                opened={isModalVisible || isEditModalVisible}
                onClose={() => {
                    setIsModalVisible(false);
                    setIsEditModalVisible(false);
                    form.reset();
                }}
                title={
                    <Text size="lg" fw={600}>
                        {isEditModalVisible ? '编辑病虫害' : '新建病虫害'}
                    </Text>
                }
                centered
            >
                <form onSubmit={form.onSubmit(isEditModalVisible ? handleEditSubmit : handleAdd)}>
                    <Stack gap="md">
                        <TextInput
                            label="英文名称"
                            placeholder="请输入英文名称"
                            {...form.getInputProps('en_name')}
                        />
                        <TextInput
                            label="中文名称"
                            placeholder="请输入中文名称"
                            {...form.getInputProps('cn_name')}
                        />
                        <TextInput
                            label="图片链接"
                            placeholder="请输入图片链接"
                            {...form.getInputProps('img_url')}
                        />
                        <Textarea
                            label="病虫害描述"
                            placeholder="请输入病虫害描述"
                            autosize
                            minRows={3}
                            maxRows={6}
                            {...form.getInputProps('description')}
                        />
                        <Textarea
                            label="防治建议"
                            placeholder="请输入防治建议"
                            autosize
                            minRows={3}
                            maxRows={6}
                            {...form.getInputProps('suggestion')}
                        />
                        <Group justify="flex-end" mt="md">
                            <Button variant="light" onClick={() => {
                                setIsModalVisible(false);
                                setIsEditModalVisible(false);
                                form.reset();
                            }}>取消</Button>
                            <Button type="submit" loading={loading}>确定</Button>
                        </Group>
                    </Stack>
                </form>
            </Modal>
        </Stack>
    );
};

export default PlantDiseaseManagement;